package de.placidi.pressreview.textprocessing;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import de.placidi.pressreview.parsing.CountedWord;

/**
 * 
 * Represents the neighbors of a word in a sentence. 
 * In this model a neighbor is a word which occurs in the same sentence as the specified word. 
 * 
 * @author Alexander Placidi
 *
 */
public final class AdjacentWords {
	
	private String word;
	private HashMap<String, Integer> neighbors;
	private List<CountedWord> neighborsList;
	
	public AdjacentWords(String word) {
		neighbors = new HashMap<>();
		neighborsList = new ArrayList<>();
		this.word = word;
	}
	
	public void addNeighbor(String n) {
		if (neighbors.containsKey(n) & !n.equals(word)) {
			Integer f = neighbors.get(n) + 1;
			neighbors.put(n, f);
		} else {
			neighbors.put(n, 1);
		}
	}
	
	public void addNeighbor(List<String> list) {
		for (String n : list) {
			if (neighbors.containsKey(n) & !n.equals(word)) {
				Integer f = neighbors.get(n) + 1;
				neighbors.put(n, f);
			} else {
				if (!n.equals(word)) neighbors.put(n, 1);
			}
		}
		
	}
	
	/**
	 * Get the three most frequent neighbors. 
	 * 
	 * @return
	 */
	public List<String> getTopThree() {
		for (Entry<String, Integer> entry : neighbors.entrySet()) {
			neighborsList.add(new CountedWord(entry.getKey(), entry.getValue()));
		}
		Collections.sort(neighborsList);
		List<String> topThree = new ArrayList<>();
		
		Integer top = 3;
		for (int i = 0; i < neighborsList.size(); i++) {
			if (i < top) {
				topThree.add(neighborsList.get(i).getWord());
			} else {
				break;
			}
		}
		
		return topThree;
		
	}

	public HashMap<String, Integer> getNeighbors() {
		return neighbors;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((word == null) ? 0 : word.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AdjacentWords other = (AdjacentWords) obj;
		if (word == null) {
			if (other.word != null)
				return false;
		} else if (!word.equals(other.word))
			return false;
		return true;
	}
	
	
}
